<?php
declare(strict_types=1);

namespace app\common\model\delivery;

use app\common\model\Admin;
use app\common\model\Qrcode;
use app\common\model\User;
use think\facade\Db;
use app\common\model\base\BaseModel;
use app\common\model\base\ConstTraits;

class Channel extends BaseModel
{

    use ConstTraits;

    const SETTLE_TYPE=[
        'sale_pay'=>'在线零售',
        'month'=>'账单月结',
        'underline'=>'货到付款'
    ];

    protected $append=['user','settle'];

    public function getUserAttr($data,$row)
    {
        if(!isset($row['user_id']) || !$row['user_id']){
            return [];
        }
        return User::whereIn('id',$row['user_id'])->cache('channel-user-'.$row['user_id'],3600*24)->field('id,nickname,avatar')->select();
    }

    public function getDeliveryEndtimeAttr($data,$row)
    {
        return substr($data,0,5);
    }

    public function getSettleAttr($data,$row)
    {
        return self::SETTLE_TYPE;
    }

    public function getGoodsAttr($data,$row)
    {
        if(!$row['goods']){
            return [];
        }
        $goods=Goods::whereIn('id',$row['goods'])->where('status','normal')->cache('channel-goods-'.$row['goods'],3600*24)->with(['spec'])->field('id,name,des,icon,img')->select();
        $goods=$goods->toArray();
        return $goods;
    }

    public function getXunjiaGoodsAttr($data,$row)
    {
        if(!$row['xunjia_goods']){
            return [];
        }
        $goods=Goods::whereIn('id',$row['xunjia_goods'])->where('status','normal')->cache('channel-xunjia-goods-'.$row['xunjia_goods'],3600*24)->with(['spec'])->field('id,name,des,icon,img')->select();
        $goods=$goods->toArray();
        foreach ($goods as $key=>$value){
            foreach ($goods[$key]['spec'] as $jey=>$item){
                unset($goods[$key]['spec'][$jey]['price']);
            }
        }
        return $goods;
    }

    public static function wuliu($channel)
    {
        $now=time();
        $today=date('Y-m-d',$now);
        $prefix=getDbPrefix();
        $sql="
            SELECT 
            customer.id,
            customer.name,
            customer.latitude,
            customer.longitude,
            orders.count,
            orders.un_receive,
            gird.id as gird_id,
            gird.gird_title,
            gird.area_range
            from {$prefix}customer customer
            INNER JOIN {$prefix}channel_gird gird on customer.gird_id=gird.id
            LEFT JOIN (SELECT customer_id,ISNULL(receive_time) un_receive,count(1) as count from {$prefix}channel_order where channel_id={$channel->id} and deletetime is null and is_cancel=0 and delivery_day='{$today}' GROUP BY customer_id,un_receive) orders on orders.customer_id=customer.id
        ";
        $list = Db::query($sql);
        $rx = [];
        foreach ($list as $value) {
            if (!isset($rx[$value['gird_id']])) {
                $rx[$value['gird_id']] = [];
            }
            array_push($rx[$value['gird_id']], $value);
        }
        $rx = array_values($rx);
        $r=[];
        foreach ($rx as $value) {
            $store_id = [];
            $customers = [];
            $weixiadan=0;
            $un_receive=0;
            $orders = [0,0];
            foreach ($value as $bill) {
                if (!in_array($bill['id'], $store_id)) {
                    $store_id[] = $bill['id'];
                }
                if(!isset($customers[$bill['id']])){
                    $customers[$bill['id']]=[
                        'id'=>$bill['id'],
                        'name'=>$bill['name'],
                        'latitude'=>$bill['latitude'],
                        'longitude'=>$bill['longitude'],
                        'type'=>'weixiadan'
                    ];
                }
                if (!$bill['count']) {
                    $weixiadan++;
                    continue;
                }
                //总订单数
                $orders[0] += $bill['count'];
                if ($bill['un_receive']) {
                    $orders[1] += $bill['count'];
                    $customers[$bill['id']]['type']='unreceive';
                    $un_receive++;
                }
                if($customers[$bill['id']]['type']!=='unreceive'){
                    $customers[$bill['id']]['type']='receive';
                }
            }
            $r[] = [
                'gird_id' => $value[0]['gird_id'],
                'gird_title' => $value[0]['gird_title'],
                'area_range' => $value[0]['area_range'],
                //店铺总数
                'total_store'=>count($store_id),
                //下单店铺数[下单总店铺数，送达]
                'store' => [count($store_id)-$weixiadan,count($store_id)-$weixiadan-$un_receive],
                //下单订单[订单总数，送达]
                'orders'=>[$orders[0],$orders[0]-$orders[1]],
                'customers' => $customers,
            ];
        }
        return $r;
    }

    public static function driver($gird_ids)
    {
        $list=ChannelGird::whereIn('id',$gird_ids)->select();
        $drivers=[];
        foreach ($list as $value){
            if(!$value->drivers){
                continue;
            }
            $drivers=array_merge($drivers,explode(',',$value->drivers));
        }
        if(count($drivers)===0){
            return [];
        }
        $begin=strtotime(date('Y-m-d 00:00:00',time()));
        $end=time();
        $prefix=getDbPrefix();
        $sql="SELECT MAX(id) as id FROM {$prefix}driver_position WHERE (createtime between {$begin} and {$end}) and driver_id in (".implode(',',$drivers).") GROUP BY driver_id";
        $pids=Db::query($sql);
        $ids=[];
        foreach ($pids as $v){
            $ids[]=$v['id'];
        }
        $list=DriverPosition::with(['driver'])
            ->whereIn('id',$ids)
            ->select();
        foreach ($list as $value){
            $value['createtime']=date('H:i:s',$value['createtime']);
        }
        return $list;
    }

    public static function getChannelAndSeller($qrcode_id=null)
    {
        $channel_id=0;
        $seller='';
        if($qrcode_id){
            $qrcode=Qrcode::find($qrcode_id);
            $foreign_key=json_decode($qrcode->foreign_key,true);
            $channel_id=$foreign_key['channel_id'];
            if($foreign_key['seller_id']){
                $seller=Seller::find($foreign_key['seller_id']);
            }
        }
        if($channel_id){
            $channel=self::find($channel_id);
        }else{
            $channel=self::where(['is_default'=>1])->find();
        }
        return compact('channel','seller');
    }
}
